import React, { useState } from 'react';
import styles from './index.less';
import { useDebounceFn } from 'ahooks';
import { Select, Form, Button, DatePicker, ConfigProvider, message } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import moment from 'moment';

import { UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { Pointer, PageLoading, TRDefault } from '@/components/index.js';
import { export_json_to_excel } from '@/utils/fileExport.js';
import {
  tenDaysTypeOptions,
  tenDaysSecondsOptions,
  pointConvert,
  dateTimeorderOptions,
  descrip,
} from '@/pages/ETrade/MediumAndLongTermMarket/constant.js';
import { fetchGetLongTermForecastPrice } from '@/pages/ETrade/MediumAndLongTermMarket/services.js';
import BaseTable from '../BaseTable';
import { ChartLongTermPriceFocast, ChartLongTermPriceFocast_shandong } from '../Charts/index.js';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYYMMDD';
let isFirst = false;

const LongTermPriceFocast = (props: any) => {
  const {
    marketList,
    marketId,
    provinceId,
    remSize,
    date,
    dateTimeorderType,
    tenDaysType: type,
    month,
    tenDays,
    unitId,
    buttonPermissions,
    point,
  } = props;
  const [loading, setLoading] = useState(true),
    [longTermPriceFocastData, setLongTermPriceFocastData] = useState<any>(),
    [tableData, setTableData] = useState<any>([]),
    [unitList, setUnitList] = useState([]),
    [tableHeader, setTableHeader] = useState<any>([]),
    [tenDaysType, setTenDaysType] = useState(type),
    [market, setMarketId] = useState(marketId),
    [region, setRegion] = useState(provinceId),
    [pointerTypeShanxi, setPointerTypeShanxi] = useState(point),
    [pointerTypeShandong, setPointerTypeShandong] = useState(point),
    [dateTimeorderTypeShandong, setDateTimeorderTypeShandong] = useState(dateTimeorderType),
    [tenDaysOptions, setTenDaysOptions] = useState(tenDaysSecondsOptions),
    [form] = Form.useForm();
  const onRegionChange = (val: any, opt: any) => {
    setMarketId(val);
    setRegion(opt.provinceId);
    // setTenDaysType(type);
    const list = opt?.children || [];
    setUnitList(list);
    if (!isFirst) {
      form.setFieldsValue({ unit: list[0].value, region: opt.provinceId });
    }
    isFirst = false;
  };
  const defaultRequest = () => {
    isFirst = true;
    const opt = marketList.find((i: any) => i.value === marketId);
    onRegionChange(marketId, opt);
    form.submit();
  };

  React.useEffect(() => {
    defaultRequest();
  }, []);

  const getLongTermPriceFocast = async (values: any) => {
    setLoading(true);
    setTableData([]);
    const param: any = {
      provinceId: values.region,
      marketId,
    };
    if (values.region === '37') {
      param.type = values.dateTimeorderType === '日期' ? 'date' : 'point';
      param.endDate = moment(values.dateRange[1]).format('YYYY-MM-DD');
      param.startDate = moment(values.dateRange[0]).format('YYYY-MM-DD');
      param.stationId = values.unit;
      param.pointType = values.pointerTypeShandong;
    } else {
      param.endDate =
        values.tenDaysType === '月'
          ? moment(values.month).endOf('month').format('YYYY-MM-DD')
          : moment(values.month).set('date', values.tenDays.split('-')[1]).format('YYYY-MM-DD');
      param.startDate =
        values.tenDaysType === '月'
          ? moment(values.month).startOf('month').format('YYYY-MM-DD')
          : moment(values.month).set('date', values.tenDays.split('-')[0]).format('YYYY-MM-DD');
      param.forecastStep = values.tenDaysType === '月' ? 30 : 10;
      param.stationId = marketList[0].value;
      param.pointType = values.pointerTypeShanxi;
    }
    const res = await fetchGetLongTermForecastPrice(param);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data?.length) return;
      let data = res.data;
      let _tableData: any = [];
      let XAXIS: any = [];
      if (values.region !== '37') {
        data = data[0];
        XAXIS = data.referencePrice.map((t: any, i: any) =>
          pointConvert(i + 1, data?.referencePrice?.length),
        );
        setLongTermPriceFocastData({
          XAXIS,
          realPrice: data.orgPrice,
          focastPrice: data.forecastPrice,
          referenPrice: data.referencePrice,
          maxPrice: data.upLimitPrice,
          minPrice: data.lowLimitPrice,
        });
        _tableData = [
          {
            title: '实际电价',
          },
          {
            title: '预测电价',
          },
          {
            title: '参考电价',
          },
          {
            title: '上限电价',
          },
          {
            title: '下限电价',
          },
        ];
        XAXIS.forEach((t: any, i: any) => {
          _tableData[0][t] = data.orgPrice[i] || '-';
          _tableData[1][t] = data.forecastPrice[i] || '-';
          _tableData[2][t] = data.referencePrice[i];
          _tableData[3][t] = data.upLimitPrice[i];
          _tableData[4][t] = data.lowLimitPrice[i];
        });
      } else {
        const focastPrice: any = [];
        data.forEach((t: any) =>
          Object.entries(t).forEach((_t: any) =>
            _t[1].forEach((_t_: any, _i_: number) => {
              XAXIS.push(
                param.type === 'point'
                  ? `${moment(_t[0]).format('MMDD')} ${pointConvert(_i_ + 1, _t[1].length)}`
                  : `${moment(_t[0]).format('MMDD')}`,
              );
              focastPrice.push(_t_);
            }),
          ),
        );
        setLongTermPriceFocastData({
          XAXIS,
          focastPrice,
          isPoint: param.type === 'point',
        });
        _tableData = [
          {
            title: '预测电价',
          },
        ];
        XAXIS.forEach((t: any, i: any) => {
          _tableData[0][t] = focastPrice[i];
        });
      }

      setTableData(_tableData);
      setTableHeader(
        XAXIS.map((t: any) => ({
          name: t,
          field: t,
        })),
      );
    }
  };
  const _onFinish = useDebounceFn(
    (values: any) => {
      getLongTermPriceFocast(values);
    },
    { wait: 500 },
  );
  // 导出
  const onexport = () => {
    if (!tableData.length) return;
    const hasSave =
      buttonPermissions.filter(
        (item: any) => item.menuCode === 'LongPeriodAvgElectricityPriceForecastExport',
      ).length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const filename = `长周期日均电价预测`;
    const params: any = {
      multiHeader: [],
      header: ['类型'],
      data: [],
      merges: [],
      filename,
    };
    const filterVal: string[] = ['title'];
    tableHeader.map((item: { name: string; field: string }) => {
      params.header.push(item.name);
      filterVal.push(item.name);
    });
    params.data = tableData.map((v: Record<string, any>) => {
      return filterVal.map((j) => {
        if (j === 'title') {
          return v[j]; // 导出表格第一列
        } else if (v && (v[j] || parseFloat(v[j]) === 0)) {
          return v[j] === '-' ? v[j] : Math.round(v[j] * 100) / 100;
        }
      });
    });
    export_json_to_excel(params);
  };
  const initialValues = () => ({
    market: marketId,
    region: provinceId,
    tenDaysType: type,
    unit: unitId,
    month: month,
    tenDays: tenDays,
    dateTimeorderType,
    dateRange: date,
    pointerTypeShanxi: point,
    pointerTypeShandong: point,
  });
  const onMonthChange = (val: any) => {
    form.setFieldsValue({ tenDays: '1-10' });
    tenDaysSecondsOptions[2].label = `21-${moment(val).daysInMonth()}日`;
    setTenDaysOptions(tenDaysSecondsOptions);
  };
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      setPointerTypeShanxi(point);
      setPointerTypeShandong(point);
      setDateTimeorderTypeShandong(dateTimeorderType);
      setTenDaysType(type);
      form.setFieldsValue({
        pointerTypeShanxi: point,
        pointerTypeShandong: point,
        dateTimeorderType,
      });
      defaultRequest();
    },
    { wait: 500 },
  );
  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <div className={styles.header}>
          <Form
            form={form}
            initialValues={initialValues()}
            className={styles.formStyles}
            onFinish={_onFinish.run}
          >
            <Form.Item
              name="market"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择省份' }]}
            >
              <Select
                style={{ width: 200 }}
                placeholder="选择省份"
                showSearch
                onChange={onRegionChange}
                options={marketList}
                filterOption={(input, option) => {
                  return (option?.label as unknown as string)
                    .toLowerCase()
                    .includes(input.toLowerCase());
                }}
              />
            </Form.Item>
            <Form.Item noStyle name="region" />
            {region === '37' ? (
              <>
                <Form.Item
                  name="unit"
                  className={styles.cell_item}
                  rules={[{ required: true, message: '请选择交易单元' }]}
                >
                  <Select
                    showSearch={true}
                    style={{ width: 200 }}
                    placeholder="请选择交易单元"
                    options={unitList}
                    filterOption={(input, option) => {
                      return (option?.label as unknown as string)
                        .toLowerCase()
                        .includes(input.toLowerCase());
                    }}
                  />
                </Form.Item>
                <Form.Item name="dateTimeorderType" className={styles.cell_item}>
                  <Pointer
                    className={styles.font}
                    options={dateTimeorderOptions}
                    data={dateTimeorderTypeShandong}
                    onChange={(e: any) => {
                      setDateTimeorderTypeShandong(e.target.value);
                      form.setFieldsValue({ dateTimeorderType: e.target.value });
                    }}
                  />
                </Form.Item>
                <Form.Item name="dateRange" className={styles.cell_item}>
                  <RangePicker
                    className={styles.font}
                    style={{ width: 260 }}
                    allowClear={false}
                    format={dateFormat}
                    separator={'-'}
                  />
                </Form.Item>
                {dateTimeorderTypeShandong !== '日期' ? (
                  <Form.Item name="pointerTypeShandong" className={styles.cell_item}>
                    <Pointer
                      className={styles.font}
                      data={pointerTypeShandong}
                      onChange={(e: any) => {
                        setPointerTypeShandong(e.target.value);
                        form.setFieldsValue({ pointerTypeShandong: e.target.value });
                      }}
                    />
                  </Form.Item>
                ) : null}
              </>
            ) : (
              <>
                <Form.Item name="tenDaysType" className={styles.cell_item}>
                  <Pointer
                    className={styles.font}
                    options={tenDaysTypeOptions}
                    data={type}
                    onChange={(e: any) => {
                      setTenDaysType(e.target.value);
                      onMonthChange(form.getFieldValue('month'));
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="month"
                  className={styles.cell_item}
                  rules={[{ required: true, message: '请选择月份' }]}
                >
                  <DatePicker
                    className={styles.month}
                    style={{ width: 140 }}
                    onChange={(e: any) => {
                      form.setFieldsValue({ month: e });
                      onMonthChange(e);
                    }}
                    picker="month"
                    format={'YYYYMM'}
                  />
                </Form.Item>
                {tenDaysType === '旬' ? (
                  <Form.Item
                    name="tenDays"
                    className={styles.cell_item}
                    rules={[{ required: true, message: '请选择旬' }]}
                  >
                    <Select
                      className={styles.font}
                      style={{ width: 140 }}
                      options={tenDaysOptions}
                    />
                  </Form.Item>
                ) : (
                  ''
                )}
                <Form.Item name="pointerTypeShanxi" className={styles.cell_item}>
                  <Pointer
                    className={styles.font}
                    data={pointerTypeShanxi}
                    onChange={(e: any) => {
                      setPointerTypeShanxi(e.target.value);
                      form.setFieldsValue({ pointerTypeShanxi: e.target.value });
                    }}
                  />
                </Form.Item>
              </>
            )}
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
            <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
              重置
            </Button>
          </Form>
          <Button
            type="link"
            icon={<UploadOutlined />}
            disabled={!tableData.length}
            onClick={onexport}
          >
            导出
          </Button>
        </div>
        {loading ? (
          <PageLoading />
        ) : (
          <div className={styles.content}>
            {tableData?.length && tableHeader?.length ? (
              <>
                <div style={{ height: 'calc(100% - 200px)' }}>
                  {longTermPriceFocastData?.maxPrice ? (
                    <ChartLongTermPriceFocast
                      data={longTermPriceFocastData}
                      scale={remSize / 100}
                    />
                  ) : (
                    <ChartLongTermPriceFocast_shandong
                      data={longTermPriceFocastData}
                      scale={remSize / 100}
                    />
                  )}
                </div>
                <div style={{ paddingBottom: 24, marginTop: 28 }}>
                  <BaseTable
                    tableData={tableData}
                    tableHeader={tableHeader}
                    hasStickyScroll={false}
                  />
                </div>
              </>
            ) : (
              <TRDefault
                type="emptysm"
                message={region === '14' || region === '37' ? '暂无数据' : descrip}
              />
            )}
          </div>
        )}
      </div>
    </ConfigProvider>
  );
};

export default LongTermPriceFocast;
